/**
 */

import moment from 'moment'
import Csv from './export/csv'
import ExportCsv from './export/export-csv'

/**
 * check browser type
 * @param window
 * @returns {boolean}
 */
export function checkBrowser () {
  // Opera 8.0+
  // const isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;

  // Firefox 1.0+
  const isFirefox = typeof InstallTrigger !== 'undefined'

  // Safari 3.0+ "[object HTMLElementConstructor]"
  // const isSafari = /constructor/i.test(window.HTMLElement) || (function(p) {
  //   return p.toString() === '[object SafariRemoteNotification]';
  // }(!window.safari || safari.pushNotification));

  // Internet Explorer 6-11
  // const isIE = /* @cc_on!@*/ false || !!document.documentMode;

  // Edge 20+
  // const isEdge = !isIE && !!window.StyleMedia;

  // Chrome 1+
  const isChrome = !!window.chrome && !!window.chrome.csi && !!window.chrome.loadTimes; //old = !!window.chrome && !!window.chrome.webstore

  // Blink engine detection
  // const isBlink = (isChrome || isOpera) && !!window.CSS;

  return isChrome || isFirefox
}

/**
 * 原生计算 元素 的 offsetLeft, offsetTop
 *
 * @export
 * @param {any} elem
 * @returns
 */
export function eleOffset (elem) {
  let box

  if (!elem || !elem.ownerDocument) {
    return null
  }

  try {
    box = elem.getBoundingClientRect()
  } catch (e) {
    console.log(e)
  }

  const doc = elem.ownerDocument
  const docElem = doc.documentElement
  const clientTop = docElem.clientTop || doc.body.clientTop || 0
  const clientLeft = docElem.clientLeft || doc.body.clientLeft || 0
  const scrollTop =
    window.pageYOffset || docElem.scrollTop || doc.body.scrollTop
  const scrollLeft =
    window.pageXOffset || docElem.scrollLeft || doc.body.scrollLeft
  const top = box.top + scrollTop - clientTop
  const left = box.left + scrollLeft - clientLeft

  return {
    left,
    top
  }
}

/**
 * 首字母大写
 *
 * @export
 * @param {any} str
 * @returns
 */
export function firstUpperCase (str) {
  const reg = /\b(\w)|\s(\w)/g
  return str.replace(reg, m => m.toUpperCase())
}

/**
 *
 * 代理事件
 * @export
 * @param {any} func
 * @param {any} context
 * @returns
 */
export function proxy (func, context) {
  return (...args) => {
    func.apply(context, args)
  }
}

/**
 * 解析
 *
 * @export
 * @param {any} str
 * @param {any} args
 * @returns
 */
export function parseHtml (...args) {
  if (args.length > 1) {
    let result = args[0]
    if (args.length === 2 && typeof args === 'object') {
      Object.keys(args).forEach(key => {
        const reg = new RegExp(`({${key}})`, 'g')
        result = result.replace(reg, args[key])
      })
    } else {
      for (let i = 1; i < arguments.length; i += 1) {
        if (args[i] === undefined) {
          return ''
        }
        const reg = new RegExp(`({[${i - 1}]})`, 'g')
        result = result.replace(reg, args[i])
      }
    }
    return result
  }
  return ''
}

/**
 * 深拷贝
 *
 * @export
 * @param {any} obj
 * @returns
 */
export function deepClone (obj) {
  let result
  const oClass = Object.prototype.toString.call(obj).slice(8, -1)
  // 确定result的类型
  if (oClass === 'Object') {
    result = {}
  } else if (oClass === 'Array') {
    result = []
  } else {
    return obj
  }
  Object.keys(obj).forEach(key => {
    const copy = obj[key]
    const copyClass = Object.prototype.toString.call(copy).slice(8, -1)
    if (copyClass === 'Object') {
      result[key] = deepClone(copy) // 递归调用
    } else if (copyClass === 'Array') {
      result[key] = deepClone(copy)
    } else {
      result[key] = obj[key]
    }
  })
  return result
}

/**
 * 将秒数格式化为倒计时： 00:00
 *
 * @export
 * @param {any} value
 * @returns
 */
export function formatCountDown (value) {
  if (value <= 0) {
    return '00:00'
  }
  let result = ''
  value *= 1000
  const hours = Math.floor(moment.duration(value).asHours())
  if (hours > 0) {
    result += hours < 10 ? `0${hours}:` : `${hours}:`
    value -= hours * 3600 * 1000
  }
  const minutes = Math.floor(moment.duration(value).asMinutes())
  result += minutes < 10 ? `0${minutes}:` : `${minutes}:`
  value -= minutes * 60 * 1000
  const seconds = Math.floor(moment.duration(value).asSeconds())
  result += seconds < 10 ? `0${seconds}` : `${seconds}`
  return result
}

/**
 * 计算字符长度
 *
 * @export
 * @param {any} value
 * @returns
 */
export function calculateStrLength (value) {
  if (!value) {
    return ''
  }
  value = '' + value
  let strLength = 0
  const strLen = value.length
  for (let i = 0; i < strLen; i++) {
    const a = value.charAt(i)
    strLength++
    if (encodeURI(a).length > 4) {
      // 中文字符的长度经编码之后大于4
      strLength += 1
    }
  }
  return strLength
}

export function cutStr (value, limit) {
  if (!value) {
    return ''
  }
  value = '' + value
  let strLength = 0
  const strLen = value.length
  let strCut = ''
  for (let i = 0; i < strLen; i++) {
    const a = value.charAt(i)
    strLength++
    if (encodeURI(a).length > 4) {
      // 中文字符的长度经编码之后大于4
      strLength += 1
    }
    strCut = strCut.concat(a)
    if (strLength >= limit) {
      strCut = strCut.concat('...')
      return strCut
    }
  }

  // 如果给定字符串小于指定长度，则返回源字符串；
  if (strLength < limit) {
    return value
  }
}

/**
 * 导出为csv文件
 *
 * @export
 * @param {any} params
 */
export function exportCsv (params) {
  if (params.filename) {
    if (params.filename.indexOf('.csv') === -1) {
      params.filename += '.csv'
    }
  } else {
    params.filename = 'table.csv'
  }
  let columns = []
  let datas = []
  if (params.columns && params.data) {
    columns = params.columns
    datas = params.data
  } else {
    columns = this.columns
    if (!('original' in params)) params.original = true
    datas = params.original ? this.data : this.rebuildData
  }
  let noHeader = false
  if ('noHeader' in params) noHeader = params.noHeader
  const data = Csv(columns, datas, ',', noHeader)
  ExportCsv.download(params.filename, data)
}

/**
 * 导出csv 数据预处理操作
 *
 * @export
 * @param {any} filename
 * @param {any} csvData
 */
export function exportCsvData (filename, csvData) {
  let columns = []
  if (csvData[0]) {
    Object.keys(csvData[0]).map((k) => {
      columns.push({
        key: k
      })
    })
  }
  exportCsv({
    filename: filename,
    columns: columns,
    data: csvData
  })
}

/**
 * 比较课程ID是否相等
 *
 * @export
 * @param {any} c1
 * @param {any} c2
 * @returns
 */
export function compareCourseId (c1, c2) {
  console.log(c1, c2)
  console.log((c1.replace(/\//g, '%2F') === c2.replace(/\//g, '%2F')))
  return (c1.replace(/\//g, '%2F') === c2.replace(/\//g, '%2F'))
}

/**
 * 过滤处理课程ID中的 / 字符
 *
 * @export
 * @param {any} cid
 * @returns
 */
export function filterCourseId (cid) {
  return cid.replace(/\//g, '%2F')
}
